package com.dp.service.impl3;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.persistence.NoResultException;
import javax.persistence.NonUniqueResultException;
import javax.persistence.Query;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.dp.pojo.JsonPage;
import com.dp.util.BookConfig;
import com.dp.util.DataMap;
import com.dp.vo.NewsExtendsChannel;
import com.dp.vo.NewsRssChannel;
import com.dp.vo.TChannels;

@Service
@Transactional
public class RsschannelServiceImpl3 extends BaseImpl {
	
	/**
	 * RSSchannel信息总记录数
	 * @param hashMap
	 * @return Integer
	 */
	public int findAllRssChannelEntityCount(DataMap hashMap){
		String rssurl = hashMap.getMapData("rssurl");
		String chanelid=(String)hashMap.get("chanelid");
		StringBuffer sqlS = new StringBuffer("SELECT count(channelid) FROM news_rsschannel WHERE 1=1");
		if(chanelid!=null&&!"".equals(chanelid)){
			sqlS.append(" channelid='" + chanelid + "'");
		}
		if(rssurl != null && !"".equals(rssurl)){
			sqlS.append(" AND rssurl like '%" + rssurl + "%'");
		}
		int i = 0;
		try {
			i=this.getOneInt();
		} catch (Exception e) {
			log.error(" findContentCommentCount fail !!!" +e.getMessage());
		}
	//	finally{this.closeAll(); }
		return i;
	}
	
	/**
	 * Find all the NewsRssChannel Entity
	 * @param hashMap
	 * @param firstrow
	 * @param maxrow
	 * @return List<NewsRssChannel>
	 */
	public List<NewsRssChannel> findAllNewsRsschannelEntity(DataMap hashMap, Integer firstrow,
			Integer maxrow){
		String rssurl = hashMap.getMapData("rssurl");
		String chanelid=(String)hashMap.get("chanelid");
		List<NewsRssChannel> queryList=null;
		try {
			StringBuffer sf = new StringBuffer("SELECT n FROM NewsRssChannel n WHERE 1=1 ");
			if(chanelid!=null&&!"".equals(chanelid)){
				sf.append(" AND n.newsRssChannelPK.newsExtendsChannel.channelId.channelId='"
					+ chanelid + "'");
			}
			//if(rssChannel!=null&&rssChannel.getNewsRssChannelPK().getRssurl()!=null&& rssChannel.getNewsRssChannelPK().getRssurl().toString().trim().length() > 0){
			if(rssurl != null && !"".equals(rssurl)){
				sf.append(" AND n.newsRssChannelPK.rssurl like '%"
						+ rssurl + "%'");
			}
			JsonPage jpage = (JsonPage)hashMap.get("jpage");
			if(jpage!=null){
				if(jpage.getSidx()!=null&&!"".equals(jpage.getSidx())){
					sf.append(" order by "+jpage.getSidx());
					sf.append(" "+jpage.getSord());
				}
			}
			logger.info("findAllNewsRsschannelEntity excute sql:"+sf.toString());
			Query query = em.createQuery(sf.toString());
			if (firstrow != null) {
				query.setFirstResult(firstrow);
			}
			if (maxrow != null) {
				query.setMaxResults(maxrow);
			}
			queryList = query.getResultList();
		} catch (Exception e) {
			logger.error(e.getMessage());
			e.printStackTrace();
		}
		return queryList;
	}

	/**
	 * Add NewsRssChannel Entity
	 * @param rssChannel
	 * @return boolean
	 */
	public boolean addNewsRssChannel(NewsRssChannel rssChannel) {
		boolean resultb=true;
		try {
			em.persist(rssChannel);
		} catch (Exception e) {
			logger.error("addNewsRssChannel fail !!!" + e.getMessage());
			resultb=false;
		}
		return resultb;
	}
	
	/**
	 * Update NewsRssChannel Entity
	 * @param rssChannel
	 * @return boolean
	 */
	public boolean updateNewsRssChannel(NewsRssChannel rssChannel,String oldchid,String oldrssurl) {
		String jpql="update news_rsschannel set rssurl='"+rssChannel.getNewsRssChannelPK().getRssurl()+"'," +
				"channelid="+rssChannel.getNewsRssChannelPK().getNewsExtendsChannel().getChannleid()+" where " +
				"rssurl='"+oldrssurl+"' and channelid=(select channleid FROM news_extends_channel where channel_id='"+oldchid+"')";
		logger.info("updateNewsRssChannel excute sql:"+jpql);
		try {
			return this.execUpdate(jpql);
		} catch (Exception e) {
			logger.error("updateNewsRssChannel fail !!!" + e.getMessage());
			e.printStackTrace();
			return false;
		} 
	}

	/**
	 * getChannelList
	 * @return
	 */
	public List<TChannels> getChannelList1(DataMap hashMap) {
		List<TChannels> queryList= new ArrayList<TChannels>();
		try {
		String jpql = "SELECT ch FROM TChannels ch WHERE ch.status='"
				+ BookConfig.channel_status_enable + "' AND (functionName='"
				+ BookConfig.channel_song + "' OR functionName='"
				+ BookConfig.channel_last + "')";
		Object employee_id = hashMap.get("employee_id");
		Object role_id = hashMap.get("role_id");
		
		if (role_id != null) {
			if (!role_id.equals("") && StringIsNotNull(employee_id)) {
				jpql = "select ch from TChannels ch,TUserChannels uc WHERE ch.channelId=uc.channelId AND ch.status='"
						+ BookConfig.channel_status_enable
						+ "' AND (ch.functionName='"
						+ BookConfig.channel_last
						+ "' OR ch.functionName='"
						+ BookConfig.channel_song
						+ "') AND uc.employeeId='" + employee_id + "'";
			}
		}
		Query query = em.createQuery(jpql);
		queryList= query.getResultList();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return queryList;
	}
	
	public static boolean StringIsNotNull(Object str) {
        boolean b = false;
        try {
            if (!str.equals("") && !str.equals("null")) {
                b = true;
            }
        } catch (Exception e) {
        }
        return b;
    }

	/**
	 * findNewsExtendsChannelByChannel_id
	 * @param channel_id
	 * @return NewsExtendsChannel (NewsExtendsChannel id)
	 */
	public NewsExtendsChannel findNewsExtendsChannelByChannel_id(String channel_id) {
		NewsExtendsChannel newsExtendsChannel =null;
		try {
				Query query = em.createQuery("SELECT n FROM NewsExtendsChannel n WHERE channelId.channelId=:channel_id");
				query.setParameter("channel_id", channel_id);
				newsExtendsChannel=(NewsExtendsChannel)getSingleResult(query);
		} catch (Exception e) {
			logger.error("findNewsExtendsChannelByChannel_id fail !!!" + e.getMessage());
			e.printStackTrace();
		}
		return newsExtendsChannel;
	}

	
	public Object getSingleResult(Query query) {
		Object o =null;
		try {
			o = query.getSingleResult();
		} catch (NoResultException ex) {
			return null;
		} catch (NonUniqueResultException ex) {
			o = query.getResultList();
			return ((List) o).get(0);
		}
		return o;
	}
	
	public ArrayList<DataMap> findAllLastChannel(Object roleId, String userId) {
		//root
		String findSql = "select  ch.channel_id  ,ch.service_code,ch.channel_name,ch.channel_comment ,ch.function_name,ch.STATUS ,ch.ordered ,ch.created_date,ch.previous_id ,ch.primal_id ,ch.LEVEL ,ch.channel_type  ,ch.channel_hot_topics ,ch.channel_classifying_label" +"  from t_channels ch WHERE 1=1 " + 
				" AND (function_name='"+BookConfig.channel_last+"' OR function_name='"+BookConfig.channel_song+"') ";
		//normal user
		if(roleId != null && !roleId.equals(""))
		{
			findSql = "select  ch.channel_id  ,ch.service_code,ch.channel_name,ch.channel_comment ,ch.function_name,ch.STATUS ,ch.ordered ,ch.created_date,ch.previous_id ,ch.primal_id ,ch.LEVEL ,ch.channel_type  ,ch.channel_hot_topics ,ch.channel_classifying_label" +"  from t_channels ch,t_user_channels uc WHERE ch.channel_id=uc.channel_id "+
		    		" and (function_name='"+BookConfig.channel_last+"' OR function_name='"+BookConfig.channel_song+"')  " +
		    		" and uc.employee_id=(SELECT employee_id FROM t_user where user_id='" + userId + "')";
		}
		try {
			log.info("findAllLastChannel:"+findSql);
			return this.queryALLResultSet(findSql.toString());
		} catch (Exception e) {
			logger.error(" findAllLastChannel fail !!!" +e.getMessage());
			return null;
		}
	}
	
	
	public DataMap buildLastChannelMap()
    {
    	String sql = "SELECT channel_id,channel_name,function_name,previous_id FROM t_channels t";
    	HashMap<String,String> childIdAndPreiousId = new HashMap<String,String>();
    	HashMap<String,String> idAndName = new HashMap<String,String>();
    	DataMap result = new DataMap();
    	List chList = null;
    	try {
			chList = queryALLResultSet(sql);
		} catch (Exception e) {
			log.error(" NewsServiceImpl3 buildChChildIdAndPreviousIdMap fail !!!" +e.getMessage());
			e.printStackTrace();
			return null;
		}
		//首先建立两个map准备数据
		for(int i=0;i<chList.size();i++)
		{
			HashMap hashMap = (HashMap)chList.get(i);
			String channel_id = (String)hashMap.get("channel_id");
			String chName = (String)hashMap.get("channel_name");
			String fnName = (String)hashMap.get("function_name");
			String previous_id = (String)hashMap.get("previous_id");
			//先将id和name装入map
			idAndName.put(channel_id, chName);
			//channel如果是normal或者first,就装入map,key是channel_id,value是
			if(fnName.equals(BookConfig.channel_first) || fnName.equals(BookConfig.channel_normal))
			{
				childIdAndPreiousId.put(channel_id, previous_id);
			}
		}
		//build map,key:channleid value:previousid+name
		for(int i=0;i<chList.size();i++)
		{
			HashMap hashMap = (HashMap)chList.get(i);
			String channel_id = (String)hashMap.get("channel_id");
			String chName = (String)hashMap.get("channel_name");
			String fnName = (String)hashMap.get("function_name");
			String previous_id = (String)hashMap.get("previous_id");
			//如果是normal或者first,就装入map,key是channel_id,value是
			if(fnName.equals(BookConfig.channel_last) || fnName.equals(BookConfig.channel_song))
			{
				String previousChName = idAndName.get(previous_id);
				chName = chName+"="+previousChName;
				chName = getValue(childIdAndPreiousId,idAndName,previous_id,chName);
				//最上一级的频道名称必然是news,把news过滤掉
				chName = chName.substring(0,chName.lastIndexOf("="));
				String[] tmp = chName.split("=");
				String value = "";
				for(int j=tmp.length-1;j>=0;j--)
				{
					value=value+tmp[j]+"--";
				}
				value = value.substring(0,value.length()-2);
				result.put(channel_id, value);
			}
		}
    	return result;
    }
	
	
	private String getValue(HashMap<String,String> idmap,HashMap<String,String> namemap,String key,String result)
    {
    	String parentid = idmap.get(key);
    	String parentname = namemap.get(parentid);
    	if((key != null && parentid!=null) && !parentid.equals(key))
    	{
    		result = result+"="+parentname;
    		return getValue(idmap,namemap,parentid,result);
    	}
    	else
    	{
    		return result;
    	}
    }
	
}
